﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Infrastructure.Util
{
    /// <summary>
    /// Excel 文件导出
    /// </summary>
    public class ExcelHelper
    {
        /// <summary>
        /// Excel 导出文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">存储文件名</param>
        /// <param name="metaData">单元格描述</param>
        /// <param name="list">要导出的数据集</param>
        public static void ExportToExcelFile<T>(string fileName, Dictionary<string, string> metaData, List<T> list)
            where T : class, new()
        {
            //创建Excel文件的对象 工作簿(调用NPOI文件)
            IWorkbook  excelBook = null;
            string fileExt = Path.GetExtension(fileName).ToLower();
            if (fileExt == ".xlsx") { 
                excelBook = new XSSFWorkbook();
            } else if (fileExt == ".xls") 
            {
                excelBook = new HSSFWorkbook();
            } else {
                excelBook = null; }
            ICellStyle style = excelBook.CreateCellStyle();
            //创建Excel工作表
            ISheet sheet1 = excelBook.CreateSheet("sheet1");
            //获取类的所有字段
            var properties = typeof(T).GetProperties();
            //添加列头
            IRow row1 = sheet1.CreateRow(0);
            int j = 0;
            foreach (var prop in properties)
            {

                if (metaData.ContainsKey(prop.Name))
                {
                    string colName = metaData[prop.Name];
                    row1.CreateCell(j).SetCellValue(colName);
                    j++;
                }
            }

            for (int i = 0; i < list.Count; i++)
            {
                j = 0;
                row1 = sheet1.CreateRow(i + 1);
                foreach (var prop in properties)
                {
                    if (metaData.ContainsKey(prop.Name))
                    {
                        string colName = metaData[prop.Name];
                        row1.CreateCell(j).SetCellValue(prop.GetValue(list[i], null).ToString());
                        j++;
                    }
                }
            }
            //保存到指定路径
            //转为字节数组  
            using (MemoryStream stream = new MemoryStream())
            {

                excelBook.Write(stream);
                var buf = stream.ToArray();
                //保存为Excel文件  
                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                }
                excelBook.Close();


            }

        }
    }
}
